from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.shortcuts import render,reverse
from myadmin.models import Users,Types,Goods,Address,Order,OrderInfo
from django.contrib.auth.hashers import make_password, check_password
# Create your views here.

#封装数据结构
def getdata():

    data = Types.objects.filter(pid=0)     #查询集合:数组
    # print(data)
    for i in data:
        # 遍历每个顶级分类,把所属的二级分类数组,添加成data的新键值对
        i.sub = Types.objects.filter(pid = i.id)    #查询集合:数组
        for b in i.sub:
            # 遍历二级分类,把查询的商品的数组,添加成b的新键值对
            b.sub = Goods.objects.filter(typeid = b.id)
    return data

def index(request):
    # 导航数据
    data = getdata()
    # 热销数据分两块
    b = Goods.objects.filter(status = 2)[:10]
    b1 = b[:5]
    b2 = b[5:10]

    # 豆腐块数据
    c = b[6:10]

    # 热销手机
    shouji = Types.objects.get(name='手机')
    shouji2 = Types.objects.filter(pid = shouji.id)
    shouji3 = []
    for i in shouji2:
        shouji3 += i.goods_set.all()  # 所有商品

    # 影音数码

    shuma2 = Types.objects.filter(pid = 28)
    shuma3 = []
    for i in shuma2:
        shuma3 += i.goods_set.all()  # 所有商品
    print(shuma3[0].title)

    # 周边外设

    waishe2 = Types.objects.filter(pid = 31)
    waishe3 = []
    for i in waishe2:
        waishe3 += i.goods_set.all()  # 所有商品
    print(waishe3[0].title)

    # 周边外设

    peijian2 = Types.objects.filter(pid = 34)
    peijian3 = []
    for i in peijian2:
        peijian3 += i.goods_set.all()  # 所有商品
    print(peijian3[0].title)

    context = {'navlist': data,'hot1':b1,'hot2':b2,'doufu':c,'shouji3':shouji3,'shuma3':shuma3,'waishe3':waishe3,'peijian3':peijian3}

    return render(request,'home/index.html',context)

def register(request):
    #判断来路 是get 或者是post给出不同执行
    if request.method == 'GET':
        return render(request,'home/register.html')
    elif request.method == 'POST':
        print(type(request.POST['username']))
        if request.POST['username'] != '' and request.POST['password'] != '':
            ob = Users.objects.filter(username=request.POST['username']).exists()
            if ob:
                return HttpResponse('<script>alert("用户已存在");location.href="/register"</script>')
            else:
                # 存入新的用户
                newob = Users()
                newob.username = request.POST['username']
                newob.password = make_password(request.POST['password'], None, 'pbkdf2_sha256')
                newob.save()

                # 把用户信息存入session 然后直接登录成功到首页
                request.session['vipuser'] = {'username':newob.username,'pic':newob.picurl,'uid':newob.id}
                print(request.session['vipuser'])
                return HttpResponse('<script>alert("注册成功欢迎登录");location.href="/"</script>')

        else:
            return HttpResponse('<script>alert("用户名或密码不能为空");location.href="/register"</script>')

def login(request):
    # 这里 try except 用于排除空值的错误,内部嵌套的判断 尝试不用else try except不起作用
    try:
        if request.method == 'GET':
            return render(request,'home/login.html')
        elif request.method == 'POST':
            ob = Users.objects.get(username=request.POST['username'])
            if request.session['verifycode'] != request.POST['vcode']:
                return HttpResponse('<script>alert("验证码输入错误");location.href="/login"</script>')
            if ob:
                # 验证密码
                if check_password(request.POST.get('password',''),ob.password):
                    print('111111')
                    request.session['vipuser'] = {'username':ob.username,'pic':ob.picurl,'uid':ob.id}
                    return HttpResponse('<script>alert("登录成功");location.href="/"</script>')
                else:
                    return HttpResponse('<script>alert("用户名或密码错误");location.href="/login"</script>')
            else:
                return HttpResponse('<script>alert("用户名或密码错误");location.href="/login"</script>')
    except:
        return HttpResponse('<script>alert("用户名或密码错误");location.href="/login"</script>')

def loginout(request):
    # 退出登录清除保存的session即可
    request.session['vipuser'] = {}
    request.session['cartdata'] = {}
    return HttpResponse('<script>alert("登录成功");location.href="/"</script>')


#列表页
def list(request,id):
    # 如果传参为0,浏览所有商品.需要数据: 所有顶级分类,所有二级 所有商品

    obj = Types.objects.get(id=id)    # 当前类 (顶级 or 二级)
    # 如果点了顶级分类手机:需要的数据: 一个顶级分类,全部子类,子类所有商品
    if obj.pid == 0:
        b = Types.objects.filter(pid=id) # 所有二级
        c = []
        for i in b:
            c += i.goods_set.all() # 所有商品
        d = c[1:5]
        content = {'a': obj, 'b': b, 'c':c,'d':d,'navlist':getdata()}
    # 如果点子类华为手机:需要的数据: 一个顶级分类,全部子类,所选中子类的商品
    else:
        a = Types.objects.get(id = obj.pid) # 顶级
        b = Types.objects.filter(pid =a.id)    # 所有二级
        c = Goods.objects.filter(typeid = id) # 当前所有商品
        d = c[1:5]
        content = {'a':a,'b':b,'c':c,'d':d,'navlist':getdata()}

    # else:
    #     a = Types.objects.filter(pid=0)
    #     b = []
    #     c = []
    #     for i in a:
    #         b += Types.objects.filter(pid = i.id)
    #         print(i)
    #     for i in b:
    #         c += Goods.objects.filter(typeid = i.id)
    #     print(b)
    #     print(c)
    #     d = {'all':0}
    #     content = {'a': a,'b':b,'c': c,'d':d ,'navlist': getdata()}

    return render(request,'home/list.html',content)


# 详情页
def info(request,id):
    goodsinfo = Goods.objects.get(id=id)
    content = {'navlist':getdata(),'goodsinfo':goodsinfo}
    return render(request,'home/info.html',content)

# 加入购物车
def cartadd(request):
    try:
        id = request.GET['gid']
        num = int(request.GET['num'])
        # 购物车先查询一次session.['cart'],如果有相同id商品,就把num加上,不相同,就追加
        cartdata = request.session.get('cartdata',{})
        if id in cartdata:
            # 修改num
            cartdata[id]['num'] += num
        else:
            # 新数据追加到session cartdata中
            goods = Goods.objects.get(id=id)
            cartdata[id] = {'id':goods.id,'title':goods.title,'price':str(goods.price),'pic':goods.pic,'num':num}
        # 把数据放入session 中去,必须用一个变量存入,而不是直接操作session
        #[1:{,,,,},2:{,,,,},3:{,,,,},4:{,,,,}]
        request.session['cartdata'] = cartdata
        print(request.session['cartdata'] )
        return JsonResponse({'msg':'加入购物车成功'})
    except:
        return JsonResponse({'msg': '加入购物车失败'})


# 购物车展示
def cartlist(request):
    # print(request.session['cartdata'])
    context = {'navlist':getdata()}
    return render(request,'home/cartlist.html',context)

# 清空购物车
def cartclear(request):
    request.session['cartdata'] = {}
    return HttpResponse('<script>alert("成功清空购物车");location.href="/cartlist"</script>')

# 修改购物车数量
def cartupdate(request):
    id = request.GET['gid']
    num = request.GET['num']
    print(id,num)
    # 取出来购物车商品信息进行修改
    cartdata = request.session.get('cartdata', {})
    # print(cartdata)
    #{'21': {'price': '48.00', 'num': 2, 'id': 21, 'title': '耳机002', 'pic': '/static/pics/152713446517749.jpg'}}
    # 修改数量
    cartdata[id]['num']=num
    # 再把修改后的数据重新赋值到session['cartdata']
    request.session['cartdata'] = cartdata
    return HttpResponse('<script>location.href="/cartlist"</script>')



# 删除购物车的数据
def cartdel(request):
    # 获取商品id,在session中删除 先获取后赋值
    if len(request.session['cartdata']) > 1:
        id = request.GET['gid']
        cartdata = request.session['cartdata']
        del cartdata[id]
        request.session['cartdata'] = cartdata
        return HttpResponse('<script>location.href="/cartlist"</script>')

    else:
        request.session['cartdata'] = {}
        return HttpResponse('<script>location.href="/cartlist"</script>')

def orderconfirm(request):
    print(request.POST)
    #判断来路 GET
    if request.method == 'GET':
        # 展示用户选择的商品
        ids = request.GET['ids'].split(',')

    # 传过来的是商品id列表,通过商品id列表 遍历出session中的数据,赋值给订单orderdata 再把订单数据塞进
        # session中
        cartdata = request.session['cartdata']
        orderdata = {}
        for i in cartdata:
            if i in ids:
                orderdata[i] = cartdata[i]

        request.session['order'] = orderdata
        # print(request.session['order'])
        # 商品信息 和 用户收或地址信息,返回去展示.
        # 根据session中用户的信息,这时候用户已经通过中间件控制进行登录了,所以有用户信息
        address = Address.objects.filter(uid =request.session['vipuser']['uid']).exclude(status=10)
        # print(address)
        content = {'navlist':getdata(),'address':address}
        return render(request, 'home/orderconfirm.html', content)

    # 判断来路POST
    elif request.method == 'POST':
        # print(request.POST)
        if request.POST['adds'] == '':
            return HttpResponse(
                '<script>alert("请填写完整收货信息");location.href="/orderconfirm?ids=' + request.GET['ids'] + '"</script>')
        # 执行地址表单的添加.
        ad = Address()
        # ad.uid 就是session中存的用户uid对象,注意是对象
        ad.uid = Users.objects.get(id=request.session['vipuser']['uid'])
        ad.addname = request.POST['addname']
        ad.addphone = request.POST['addphone']
        ad.adds = request.POST['adds']


        #状态修改.判断提交上来的状态是否为1,如果为1,就让其他的地址对象的status值修改成0
        status = request.POST.get('status',0)    # 如果没选,默认为0就不需要后续操作了
        if status == '1':
            # 注意这里不能拿数据库里面status=1的修改,会拿到其他会员的地址.
            all_ad = Address.objects.filter(uid=request.session['vipuser']['uid']).filter(status=1)
            for i in all_ad:
                i.status = 0
                i.save()
        ad.status = status
        ad.save()
        # 这里ruturn 到原来页面的话,method就变成get,请求必须携带参数.否则就新页面订单创建就有问题
        return HttpResponse('<script>alert("地址添加成功");location.href="/orderconfirm?ids='+request.GET['ids']+'"</script>')


# 生成表订单: 主要是把订单的数据存入数据库.
# 地址信息:post中, 商品信息，在session['order']
def ordercreate(request):
    if request.POST['addressid'] == '':
        return HttpResponse('<script> alert("请选择或设置收货地址");window.history.back(-1);</script>')
    # print(request.POST)
        # 如果没有选择收货地址,返回上一个页面:
        #<script> alert("请设置收货信息");window.history.back(-1);</script>
    # 从session 中读取订单数据 存入order库
        # uid address地址 总价  总数  状态  添加时间

    # 然后把订单详情数据存入  orderinfo
        # 订单id 商品id 商品数量  价格
    orderdata = request.session['order']
    totalprice = 0
    totalnum = 0
    for i in orderdata:
        totalprice += float(orderdata[i]['price'])*orderdata[i]['num']
        totalnum += orderdata[i]['num']

    # order入库
    orderobj = Order()
    orderobj.uid = Users.objects.get(id=request.session['vipuser']['uid'])
    print('111')
    print(Address.objects.get(id=request.POST['addressid']))
    print('111')
    orderobj.address = Address.objects.get(id=request.POST['addressid'])

    orderobj.totalprice = totalprice
    orderobj.totalnum = totalnum
    orderobj.status = 1
    orderobj.save()

    print('111111111111111')
    # {'21': {'price': '48.00', 'num': 2, 'id': 21, 'title': '耳机002', 'pic': '/static/pics/152713446517749.jpg'}}
    # orderinfo入库 同时清除购物车session中已经入库的商品
    cartdata = request.session['cartdata']
    print(cartdata)

        # 一个订单可能有很多个详情(主要是商品详情)
    for i in orderdata:
        orderinfo = OrderInfo()
        orderinfo.orderid = orderobj
        orderinfo.gid = Goods.objects.get(id=i)
        orderinfo.num = orderdata[i]['num']
        orderinfo.price = orderdata[i]['num']
        orderinfo.save()

        # 清除购物车中被选中的商品,也就是当前orderdata列表中
        del cartdata[i]

    request.session['cartdata'] = cartdata  #删除后的重新赋值给session
    request.session['order'] = {}   #选中的商品已经生成订单入库了.这里给清空.


        # 产品销量和库存做以下修改,也可以成交以后再做修改.这里没有付款,先不做修改
        # goodsobj = Goods.objects.get(id=i)
        # goodsobj.num += orderdata[i]['num']
        # goodsobj.storage -= orderdata[i]['num']
        # goodsobj.save()
    return  HttpResponse('<script>alert("订单创建成功,请前往支付");location.href="/orderbuy?orderid='+str(orderobj.id)+'"</script>')



# 订单支付
def orderbuy(request):
    # 接收ordercreate 返回的 get请求的 订单id
    orderid = request.GET.get('orderid',None)
    if orderid:
        orderobj = Order.objects.get(id=orderid)
        # 获取订单下的商品
        content = {'navlist': getdata(),'orderobj':orderobj}
        return render(request,'home/buy.html',content)


# 我的订单
def myorder(request):
    # 获取当前登录用户 对应的所有订单
    orders = Order.objects.filter(uid=request.session['vipuser']['uid'])

    # 获取订单对应的商品数.
    # i.orderinfo_set.all()
    # print(orders[0].status,type(orders[0].status))
    content={'navlist': getdata(),'orders':orders}

    return render(request,'home/myorder.html',content)


# 取消订单

def orderdel(request,id):
    orderobj = Order.objects.get(id = id)
    if orderobj.status == 1:
        orderobj.delete()
        return HttpResponse('<script>alert("订单已取消");location.href="/myorder"</script>')
    else:
        return HttpResponse('<script>alert("该订单已付款!!!");location.href="/myorder"</script>')





# 个人中心
def member(request):
    # 需要用户信息 session中取登录保存的
    userobj = Users.objects.get(id = request.session['vipuser']['uid'])
    # 待付款订单   待发货订单
    content = {'navlist': getdata(),'userobj':userobj}
    return render(request,'home/member.html',content)



# 个人中心地址添加
def addadd(request):

    return render(request,'home/addadd.html')

def addinsert(request):
    try:
        # print(request.POST)
        addnew = Address()
        addnew.uid = Users.objects.get(id=request.session['vipuser']['uid'])
        addnew.addname = request.POST.get('addname','未知人')
        addnew.adds = request.POST.get('adds','未知地址')
        addnew.addphone = request.POST.get('addphone','18900000000')
        addnew.status = request.POST.get('status','0')
        addnew.save()
        return HttpResponse('<script>alert("添加成功");location.href="/member/addlist"</script>')
    except:
        return HttpResponse('<script>alert("填写有误");location.href="/member/addadd"</script>')


# 个人中心地址修改
def addlist(request):
    # 获取所有登录用户对应的地址
    userobj = Users.objects.get(id = request.session['vipuser']['uid'])
    addall = Address.objects.filter(uid=userobj.id).exclude(status=10)
    content = {'navlist': getdata(),'addall':addall}
    return render(request,'home/addlist.html',content)

# 个人中心地址修改
def addedit(request,id):
    addobj = Address.objects.get(id=id)
    content={'navlist': getdata(),'addobj':addobj}
    return render(request,'home/addedit.html',content)

# 地址更新
def addsave(request):
    try:
        id = request.POST['id']
        addobj = Address.objects.get(id=id)
        addobj.addname = request.POST['addname']
        addobj.adds = request.POST['adds']
        addobj.addphone = request.POST['addphone']
        # 如果修改地址发来是1 进行修改.
        # 当前user对象
        userobj = Users.objects.get(id=request.session['vipuser']['uid'])
        addall = userobj.address_set.all()
        status = request.POST.get('status',0)
        if status == '1':
            #修改所有地址的status
            for i in addall:
                i.status = 0
                i.save()
        addobj.status = status
        addobj.save()

        return HttpResponse(
            '<script>alert("修改成功");location.href="/member/addlist"</script>')
    except:
        return HttpResponse(
            '<script>alert("信息修改有误");location.href="/member/addlist"</script>')

# 删除地址
def adddel(request,id):

    # 查询盖地址是否有订单使用
    addobj = Address.objects.get(id=id)
    addobj.status = 10
    addobj.save()
    return HttpResponse('<script>alert("删除成功");location.href="/member/addlist"</script>')


